//
//  WJOverlayView.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/25.
//


import Foundation
import UIKit
import PDFKit

final class WJOverlayView: UIView {
    
    // 改为私有管理，提供公共方法来增删
    private var _boxViews: [WJPDFSignatureBoxView] = []
    
    var boxViews: [WJPDFSignatureBoxView] {
        return _boxViews
    }
    
    var isEditingEnabled: Bool = true {
        didSet {
            _boxViews.forEach { $0.isUserInteractionEnabled = isEditingEnabled }
        }
    }
    
    init() {
        super.init(frame: .zero)
        clipsToBounds = true
        backgroundColor = .clear
        isUserInteractionEnabled = true
        setupGestureRecognizers()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupGestureRecognizers() {
        let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(_:)))
        self.addGestureRecognizer(singleTapGesture)
    }
    // 添加新的 box
    func addBoxView(_ boxView: WJPDFSignatureBoxView) {
        _boxViews.append(boxView)
        boxView.delegate = self
        addSubview(boxView)
    }
    
    // 移除指定的 box
    func removeBoxView(_ boxView: WJPDFSignatureBoxView) {
        if let index = _boxViews.firstIndex(where: { $0 === boxView }) {
            _boxViews.remove(at: index)
            boxView.removeFromSuperview()
        }
    }
    
    // 移除所有 box
    func removeAllBoxViews() {
        _boxViews.forEach { $0.removeFromSuperview() }
        _boxViews.removeAll()
    }
    
    func unSelectedAllBoxView() {
        _boxViews.forEach { $0.setSelected(false) }
    }
    
    // 获取特定位置的 box（用于点击测试）
    func boxViewAtPoint(_ point: CGPoint) -> WJPDFSignatureBoxView? {
        return _boxViews.first { $0.frame.contains(point) }
    }
    
    @objc private func handleSingleTap(_ gesture: UITapGestureRecognizer) {
        unSelectedAllBoxView()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 确保所有 box 视图都在当前边界内
        for boxView in _boxViews {
            // 如果 box 超出边界，调整位置
            var frame = boxView.frame
            if frame.maxX > bounds.width {
                frame.origin.x = bounds.width - frame.width
            }
            if frame.maxY > bounds.height {
                frame.origin.y = bounds.height - frame.height
            }
            if frame.minX < 0 {
                frame.origin.x = 0
            }
            if frame.minY < 0 {
                frame.origin.y = 0
            }
            boxView.frame = frame
        }
    }
}

extension WJOverlayView: WJPDFSignatureBoxViewDelegate {
    func signatureBoxCleared(_ signatureBox: WJPDFSignatureBoxView) {
        self.removeBoxView(signatureBox)
    }
    
    func signatureBoxTapped(_ signatureBox: WJPDFSignatureBoxView) {
        unSelectedAllBoxView()
        signatureBox.setSelected(true)
    }
}
